# -*-coding: utf-8 -*-
'''
Created on 20201025

@author: xubaifu
情感分析

'''
import codecs
import jieba

import jieba.posseg as pseg

from scipy.misc import imread
from wordcloud import ImageColorGenerator
# from os import path

import matplotlib.pyplot as plt
from wordcloud import WordCloud

import numpy as np
from snownlp import SnowNLP
from snownlp import sentiment
from decimal import Decimal


# 构建停用词表
stop_words = 'txt/stopWords.txt'
stopwords = codecs.open(stop_words, 'r', encoding='utf8').readlines()
stopwords = [ w.strip() for w in stopwords ]
# 结巴分词后的停用词性 [标点符号、连词、助词、副词、介词、时语素、‘的’、数词、方位词、代词]
stop_flag = ['x', 'c', 'u', 'd', 'p', 't', 'uj', 'm', 'f', 'r', 'ul']
jieba.load_userdict("txt/userdict.txt")


class AnalysisSentiments:
    # 情感分析   
    def sentiments_analyze(self):
        f = open('txt/lufax.txt', 'r', encoding='UTF-8')
        connects = f.readlines()
        sentimentslist = []
        # 使用SnowNLP的sentiment模块训练数据
#         print('开始')
#         sentiment.train('txt/l.txt', 'txt/g.txt')
        # 保存模型
#         sentiment.save('sentiment.marshal')
        # 加载模型
        sentiment.load('sentiment.marshal')
        sum = 0
        for i in connects:
            s = SnowNLP(i)
            #分析结果保留4位小数
            result = Decimal(s.sentiments).quantize(Decimal("0.0000"))
            sentimentslist.append(float(result))
            
            if  s.sentiments > 0.5:
                sum += 1
#             print(float(result))   
            
        print('好评数：' + str(sum))
        print('总数：' + str(len(sentimentslist)))
        print('能量值：'+ str(sum/len(sentimentslist)))
        sentimentslist.sort(reverse=True)
        print(sentimentslist)
        plt.hist(sentimentslist, bins=np.arange(0, 1.01, 0.01), facecolor='g')
        plt.xlabel('Sentiments Probability')
        plt.ylabel('Quantity')
        plt.title('Analysis of Sentiments')
        plt.show()

    
if __name__ == '__main__':
    analysisSentiments = AnalysisSentiments()
    analysisSentiments.sentiments_analyze()

